import 'package:dio/dio.dart';
import 'package:flutter_fresh_mall_app/common/exception/DioException.dart';

import '../constants/ApiEndpoint.dart';

class HttpUtils {
  //私有化构造函数
  HttpUtils._internal();

  static Dio _dio;

  factory HttpUtils() => _getInstance();

  static HttpUtils _httpUtils;

  static HttpUtils _getInstance() {
    if (_httpUtils == null) {
      _httpUtils = HttpUtils._internal();
      _init();
    }
    return _httpUtils;
  }

  static void _init() {
    if (_dio == null) {
      BaseOptions baseOptions = BaseOptions(
          baseUrl: ApiEndpoint.baseUrl,
          connectTimeout: 5000, //单位毫秒
          receiveTimeout: 60000, //单位毫秒
          headers: {Headers.contentTypeHeader: Headers.contentTypeHeader});
      _dio = Dio(baseOptions);
      _dio.interceptors.add(InterceptorsWrapper(
          onRequest: (RequestOptions options) {},
          onResponse: (Response response) {},
          onError: (DioError error) {
            return exceptionHandler(error);
          }));
    }
  }

  // 网络请求统一异常处理
  static dynamic exceptionHandler(DioError error) {
    var response = error.response;
    if (response == null) {
      return DioException.of(DioException.default_code);
    }
    var containsKey = DioException.errorMap.containsKey(response.statusCode);
    if (containsKey) {
      return DioException.of(response.statusCode);
    }
    return DioException.of(DioException.default_code);
  }

  Future<Response> get(String uri, [Map<String, dynamic> param, Options options]) {
    Future<Response> result;
    if (options != null) {
      result = _dio.get(uri, queryParameters: param, options: options);
    } else {
      result = _dio.get(uri, queryParameters: param);
    }
    return result;
  }

  Future<Response> post(String uri,
      [Map<String, dynamic> param, bool isJson = true, Options ops]) {
    Future<Response> result;
    Options options;
    dynamic data;
    if (isJson) {
      options = Options(
          headers: {Headers.contentTypeHeader: Headers.jsonContentType});
    } else {
      options = Options(headers: {
        Headers.contentTypeHeader: Headers.formUrlEncodedContentType
      });
    }
    if (options != null) {
      options = ops;
    }
    if (!isJson && param != null) {
      data = FormData.fromMap(param);
    } else {
      data = param;
    }
    if (data == null) {
      result = _dio.post(uri, data: param, options: options);
    } else {
      result = _dio.post(uri);
    }
    return result;
  }
}
